import { lazy, useEffect } from "react";
import {
  Navigate,
  RouteObject,
  createHashRouter,
  useLocation,
  useNavigate,
} from "react-router-dom";
import PageA from "../pages/PageA";
import PageB from "../pages/pageB";
import Page404 from "../pages/Page404";
import Layout from "../layout";
import Login from '../pages/Login';
import Home from '../pages/Home';
import { getPagesComponent } from './utils';
import PageC from "../pages/PageC";

/**
 * 路由拦截
 */
const Interceptor = ({ children }: any) => {
  const navigate = useNavigate();

  const location = useLocation();

  useEffect(() => {
    /**
     * 路由变化了
     * 在这里写路由拦截逻辑
     */

    if (false) {
      navigate("/login", { state: { backUrl: "/pageA/a" } });
    }
    console.log('fullPath:', location.pathname + location.search);
  }, [location.key]); // 不用window.location.href因为没法检测同一个页面刷新的情况

  return children;
};

/**
 * 基础路由
 */
export const baseRoutes: RouteObject[] = [
  {
    path: "/", // 根路径会重定向到/pageA（要单独配一个，不然访问根路径会只显示Layout）
    element: <Navigate to="/home" />,
  },
  {
    path: "*",
    element: (
      <Interceptor>
        <Layout><Page404 /></Layout>
      </Interceptor>
    ),
  },
  {
    path: "/",
    element: <Interceptor><Layout /></Interceptor>,
    children: [
      {
        path: "/home",
        element: <Home />,
      },
      {
        path: "/login",
        element: <Login />,
      },
      {
        path: "/pageA",
        element: <PageA />,
      },
      {
        path: "/pageB",
        element: <PageB />,
      },
      {
        path: "/pageC/:id", // 这里的path不会继承父级，需要写全！
        element: <PageC />,
      },
    ],
  },
];

export const router = createHashRouter(baseRoutes, {
  /** 这里的basename是指/#${basename}/pageA */
  basename: "/",
});

/** 是否已添加动态路由 */
export let isAddedAsyncRoutes = false;

/**
 * 动态添加路由（根据传进来的菜单）
 */
export function addAsyncRoute(menuList: Array<any>) {
  if (isAddedAsyncRoutes) return;
  const parentRoute = router.routes.find(item => item.path === '/' && item.children);
  if (!parentRoute) return;
  
  /** 获取前路由id数据 */
  const lastId = parentRoute.children?.[parentRoute.children?.length - 1]?.id;
  const [prefixNum, iStr] = lastId?.split('-') || ['', 0];
  const i = +iStr;

  menuList.forEach((menu, index) => {
    parentRoute.children?.push({
      path: menu.path,
      // @ts-ignore
      // 这里必须用Component而不是element
      Component: lazy(getPagesComponent(menu.componentStr)),
      id: `${prefixNum}-${i + index + 1}`,
    })
  })
  isAddedAsyncRoutes = true;
}